package org.sith.taskrunner.listeners;

import org.sith.taskrunner.api.user.User;
import org.sith.taskrunner.ejb.UserThreadKeeper;

import javax.servlet.ServletRequest;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpServletRequest;

public class RequestListener implements ServletRequestListener {
    @Override
    public void requestDestroyed(ServletRequestEvent servletRequestEvent) {
        UserThreadKeeper.clear();
    }

    @Override
    public void requestInitialized(ServletRequestEvent servletRequestEvent) {
        ServletRequest request = servletRequestEvent.getServletRequest();
        if (request instanceof HttpServletRequest) {
            HttpServletRequest httpServletRequest = (HttpServletRequest) request;
            User user = (User) httpServletRequest.getSession().getAttribute("user");
            if (user != null) {
                UserThreadKeeper.setThreadUser(user);
            }

        }


    }
}
